<template>
  <div class="device-share-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>分享设备</span>
          <el-button 
            type="primary" 
            icon="el-icon-arrow-left" 
            @click="handleBack"
          >
            返回
          </el-button>
        </div>
      </template>
      
      <div v-if="!loading" class="share-content">
        <!-- 设备选择 -->
        <el-form-item label="选择设备" v-if="!selectedDeviceId">
          <el-select 
            v-model="selectedDeviceId" 
            placeholder="请选择要分享的设备"
            @change="onDeviceChange"
            filterable
          >
            <el-option 
              v-for="device in devices" 
              :key="device.id" 
              :label="device.name" 
              :value="device.id"
            />
          </el-select>
        </el-form-item>
        
        <!-- 已选设备信息 -->
        <div v-if="selectedDevice" class="selected-device-info">
          <h3>当前分享设备：{{ selectedDevice.name }}</h3>
          <p>设备编号：{{ selectedDevice.deviceNumber }}</p>
        </div>
        
        <!-- 分享设置 -->
        <el-form :model="shareForm" label-width="120px" class="share-form" v-if="selectedDevice">
          <el-form-item label="选择用户" prop="userId">
            <el-select 
              v-model="shareForm.userId" 
              placeholder="请选择要分享的用户"
              clearable
            >
              <el-option 
                v-for="user in availableUsers" 
                :key="user.id" 
                :label="user.username" 
                :value="user.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="权限设置" prop="permission">
            <el-radio-group v-model="shareForm.permission">
              <el-radio label="view">仅查看</el-radio>
              <el-radio label="control">可控制</el-radio>
              <el-radio label="admin">管理员</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="有效期">
            <el-date-picker
              v-model="shareForm.expireTime"
              type="datetime"
              placeholder="选择有效期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
            <div class="form-tip">留空表示永久有效</div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleShare" :loading="sharing">
              分享设备
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 当前分享列表 -->
        <div class="share-list-section" v-if="selectedDevice">
          <h3>当前分享列表</h3>
          <el-table :data="currentShares" style="width: 100%" v-if="currentShares.length > 0">
            <el-table-column prop="user.username" label="分享用户" />
            <el-table-column prop="permission" label="权限类型">
              <template #default="{ row }">
                <el-tag :type="getPermissionType(row.permission)">
                  {{ getPermissionText(row.permission) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="分享时间" />
            <el-table-column prop="expireTime" label="过期时间">
              <template #default="{ row }">
                {{ row.expireTime || '永久' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleRevoke(row.id)"
                >
                  撤销
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="暂无分享记录" />
        </div>
      </div>
      
      <!-- 加载中 -->
      <div v-else class="loading-state">
        <el-loading :visible="true" text="加载中..." />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { deviceApi } from '../services/api'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'DeviceShare',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loading = ref(true)
    const sharing = ref(false)
    const devices = ref([])
    const availableUsers = ref([]) // 实际应用中需要从API获取
    const currentShares = ref([]) // 当前设备的分享记录
    
    const selectedDeviceId = ref(route.query.id || '')
    
    const shareForm = ref({
      userId: '',
      permission: 'view',
      expireTime: null
    })
    
    // 计算属性：当前选中的设备
    const selectedDevice = computed(() => {
      return devices.value.find(d => d.id === selectedDeviceId.value)
    })
    
    // 加载设备列表
    const loadDevices = async () => {
      try {
        const response = await deviceApi.getAllDevices()
        devices.value = response.data || []
      } catch (error) {
        console.error('加载设备列表失败:', error)
        ElMessage.error('加载设备列表失败')
      }
    }
    
    // 加载可用用户列表（简化处理，实际需要从API获取）
    const loadAvailableUsers = () => {
      // 模拟数据，实际应用中需要从用户管理API获取
      availableUsers.value = [
        { id: '1', username: 'user1' },
        { id: '2', username: 'user2' },
        { id: '3', username: 'user3' }
      ]
    }
    
    // 加载当前设备的分享记录
    const loadCurrentShares = () => {
      // 模拟数据，实际应用中需要从API获取
      currentShares.value = [
        {
          id: '1',
          user: { username: 'user1' },
          permission: 'view',
          createdTime: '2024-01-01 10:00:00',
          expireTime: '2024-12-31 23:59:59'
        }
      ]
    }
    
    // 设备选择变化
    const onDeviceChange = () => {
      if (selectedDeviceId.value) {
        loadCurrentShares()
      }
    }
    
    // 分享设备
    const handleShare = async () => {
      if (!shareForm.value.userId) {
        ElMessage.warning('请选择要分享的用户')
        return
      }
      
      try {
        sharing.value = true
        // 这里应该调用实际的分享API
        // await deviceShareApi.shareDevice(selectedDeviceId.value, shareForm.value)
        
        ElMessage.success('设备分享成功')
        // 清空表单
        shareForm.value.userId = ''
        shareForm.value.permission = 'view'
        shareForm.value.expireTime = null
        
        // 重新加载分享列表
        loadCurrentShares()
      } catch (error) {
        console.error('分享设备失败:', error)
        ElMessage.error('分享设备失败')
      } finally {
        sharing.value = false
      }
    }
    
    // 撤销分享
    const handleRevoke = async (shareId) => {
      try {
        await ElMessageBox.confirm(
          '确定要撤销该分享吗？',
          '确认撤销',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 这里应该调用实际的撤销API
        // await deviceShareApi.revokeShare(shareId)
        
        ElMessage.success('撤销分享成功')
        // 重新加载分享列表
        loadCurrentShares()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('撤销分享失败:', error)
          ElMessage.error('撤销分享失败')
        }
      }
    }
    
    // 获取权限类型对应的标签类型
    const getPermissionType = (permission) => {
      const typeMap = {
        view: 'info',
        control: 'success',
        admin: 'warning'
      }
      return typeMap[permission] || 'info'
    }
    
    // 获取权限文本
    const getPermissionText = (permission) => {
      const textMap = {
        view: '仅查看',
        control: '可控制',
        admin: '管理员'
      }
      return textMap[permission] || permission
    }
    
    // 返回
    const handleBack = () => {
      router.back()
    }
    
    // 组件挂载时加载数据
    onMounted(async () => {
      try {
        await Promise.all([
          loadDevices(),
          loadAvailableUsers()
        ])
        
        if (selectedDeviceId.value) {
          loadCurrentShares()
        }
      } finally {
        loading.value = false
      }
    })
    
    return {
      loading,
      sharing,
      devices,
      availableUsers,
      currentShares,
      selectedDeviceId,
      selectedDevice,
      shareForm,
      onDeviceChange,
      handleShare,
      handleRevoke,
      getPermissionType,
      getPermissionText,
      handleBack
    }
  }
}
</script>

<style scoped>
.device-share-container {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.share-content {
  margin-top: 15px;
}

.selected-device-info {
  background-color: #f5f7fa;
  padding: 14px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.selected-device-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.selected-device-info p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.share-form {
  margin-bottom: 25px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.share-list-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: bold;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

/* 表格容器，确保在小屏幕上可以滚动 */
.el-table {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .device-share-container {
    padding: 8px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .card-header .el-button {
    width: 100%;
  }
  
  .selected-device-info {
    padding: 12px;
    margin-bottom: 16px;
  }
  
  .selected-device-info h3 {
    font-size: 15px;
  }
  
  .share-form {
    margin-bottom: 20px;
  }
  
  /* 调整表单元素在小屏幕上的显示 */
  :deep(.el-form) {
    width: 100%;
  }
  
  :deep(.el-form-item__label) {
    width: 100px;
    font-size: 14px;
  }
  
  :deep(.el-form-item__content) {
    width: calc(100% - 100px);
  }
  
  /* 确保表单元素在小屏幕上完全可见 */
  :deep(.el-input),
  :deep(.el-select),
  :deep(.el-date-editor) {
    width: 100%;
  }
  
  /* 调整按钮在小屏幕上的显示 */
  :deep(.el-form-item__content .el-button) {
    width: 100%;
  }
  
  /* 调整表格在小屏幕上的显示 */
  :deep(.el-table) {
    font-size: 13px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 8px;
  }
  
  /* 确保表格在小屏幕上可以滚动 */
  .share-list-section {
    overflow-x: auto;
  }
}

@media (max-width: 480px) {
  /* 进一步调整在极小屏幕上的显示 */
  :deep(.el-form--label-right) {
    --el-form-item-label-width: 90px;
  }
  
  :deep(.el-form-item__label) {
    width: 90px;
    font-size: 13px;
    padding-right: 8px;
  }
  
  :deep(.el-form-item__content) {
    width: calc(100% - 90px);
  }
  
  /* 调整输入框和选择器的高度 */
  :deep(.el-input__inner) {
    height: 34px;
    font-size: 13px;
  }
  
  /* 调整按钮尺寸 */
  :deep(.el-button) {
    padding: 8px 12px;
    font-size: 13px;
  }
  
  /* 优化表格在极小屏幕上的显示 */
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table th),
  :deep(.el-table td) {
    padding: 6px;
  }
  
  /* 调整单选按钮组的显示 */
  :deep(.el-radio-group) {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  /* 调整时间选择器的尺寸 */
  :deep(.el-date-editor) {
    --el-date-editor-width: 100%;
  }
  
  /* 确保表格在极小屏幕上可以流畅滚动 */
  .share-list-section {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }
}
</style>